package com.ruoyi.jksd.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.jksd.common.SdComponent;
import com.ruoyi.jksd.common.dto.ConveyDto;
import com.ruoyi.jksd.domain.*;
import com.ruoyi.jksd.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.jksd.mapper.XyConveyMapper;

/**
 * 会员-订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-26
 */
@Service
public class XyConveyServiceImpl implements IXyConveyService {
    @Autowired
    private XyConveyMapper xyConveyMapper;

    @Autowired
    private IXyUsersService xyUsersService;
    @Autowired
    private IXyGoodsListService xyGoodsListService;

    @Autowired
    private IXyBusinessConfigService xyBusinessConfigService;

    @Autowired
    private IXyBalanceLogService balanceLogService;


    @Autowired
    private IXyRewardLogService xyRewardLogService;

    @Autowired
    private SdComponent sdComponent;

    /**
     * 查询会员-订单
     *
     * @param id 会员-订单主键
     * @return 会员-订单
     */
    @Override
    public XyConvey selectXyConveyById(String id) {
        return xyConveyMapper.selectXyConveyById(id);
    }

    /**
     * 查询会员-订单列表
     *
     * @param xyConvey 会员-订单
     * @return 会员-订单
     */
    @Override
    public List<XyConvey> selectXyConveyList(XyConvey xyConvey) {
        return xyConveyMapper.selectXyConveyList(xyConvey);
    }

    /**
     * 新增会员-订单
     *
     * @param xyConvey 会员-订单
     * @return 结果
     */
    @Override
    public int insertXyConvey(XyConvey xyConvey) {
        return xyConveyMapper.insertXyConvey(xyConvey);
    }

    /**
     * 修改会员-订单
     *
     * @param xyConvey 会员-订单
     * @return 结果
     */
    @Override
    public int updateXyConvey(XyConvey xyConvey) {
        return xyConveyMapper.updateXyConvey(xyConvey);
    }

    /**
     * 批量删除会员-订单
     *
     * @param ids 需要删除的会员-订单主键
     * @return 结果
     */
    @Override
    public int deleteXyConveyByIds(String[] ids) {
        return xyConveyMapper.deleteXyConveyByIds(ids);
    }

    /**
     * 删除会员-订单信息
     *
     * @param id 会员-订单主键
     * @return 结果
     */
    @Override
    public int deleteXyConveyById(String id) {
        return xyConveyMapper.deleteXyConveyById(id);
    }

    @Override
    public AjaxResult doAapplyOrder(ConveyDto conveyDto) {
        String conveyId = conveyDto.getConveyId();
        Long userId = conveyDto.getUserId();
        Long goodsId = conveyDto.getGoogdsId();

//        查询对应得ID 对象
        XyConvey xyConvey = xyConveyMapper.selectXyConveyById(conveyId);
        XyUsers xyUsers = xyUsersService.selectXyUsersById(userId + "");
        XyGoodsList goodsList = xyGoodsListService.selectXyGoodsListById(goodsId);
        /**
         * 判定订单状态
         */
        if (xyConvey.getStatus().intValue() != 0 && xyConvey.getStatus().intValue() != 5) {
            return AjaxResult.error(302, "ddycl");
        }

        /**
         * 1.判断余额是否足够
         */
        if (xyConvey.getNum().compareTo(xyUsers.getBalance()) > 0) {
            //如果余额不够，
            return AjaxResult.error(301, "zhyebz");
        }
        /**
         * 修改用户余额，状态，收益
         */
        List<XyBusinessConfig> xyBusinessConfigList = xyBusinessConfigService.selectXyBusinessConfigList(null);
        XyBusinessConfig xyBusinessConfig1 = xyBusinessConfigList.get(0);
        BigDecimal trate = new BigDecimal(xyBusinessConfig1.getTradeCommissionRate());
        BigDecimal remainBal = (xyUsers.getBalance().subtract(xyConvey.getNum()));
        BigDecimal reward = xyConvey.getNum().multiply(trate.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        BigDecimal newBalance = remainBal.add(reward);
        xyUsers.setBalance(newBalance);
        xyUsersService.updateXyUsers(xyUsers);

        /**
         * 修改订单状态为完成
         */
        xyConvey.setCommission(reward);
        xyConvey.setStatus(1L);
        xyConvey.setEndtime(System.currentTimeMillis() / 1000);
        xyConveyMapper.updateXyConvey(xyConvey);


        /**
         * 添加用户收益表
         */
//        Db::name('xy_reward_log')
//                            ->insert([
//                'uid' => $v['id'],
//                'sid' => $uid,
//                'oid' => $oid,
//                'num' => $cnum * config($v['lv'] . '_d_reward'),
//        'lv' => $v['lv'],
//                'type' => 2,
//                'status' => 1,
//                'addtime' => time(),
//                            ]);
        XyRewardLog xyRewardLog = new XyRewardLog();
        xyRewardLog.setUid(userId + "");
        xyRewardLog.setSid(userId + "");
        xyRewardLog.setOid(conveyId);
        xyRewardLog.setNum(reward);
        xyRewardLog.setType(2L);
        xyRewardLog.setStatus(1L);
        xyRewardLog.setAddtime(System.currentTimeMillis() / 1000 + "");
        xyRewardLogService.insertXyRewardLog(xyRewardLog);
//        xyRewardLogService

        /**
         * 添加账户变动明细
         */
        XyBalanceLog balanceLog = new XyBalanceLog();
        balanceLog.setUid(xyUsers.getId());
        balanceLog.setOid(xyConvey.getId());
        balanceLog.setNum(xyConvey.getNum());
        balanceLog.setStatus(2L);
        balanceLog.setAddtime(System.currentTimeMillis() / 1000);
        balanceLog.setType(2L);//
        balanceLogService.insertXyBalanceLog(balanceLog);

        /**
         * 添加账户变动明细-reward
         */
        XyBalanceLog rewardbalanceLog = new XyBalanceLog();
        rewardbalanceLog.setUid(xyUsers.getId());
        rewardbalanceLog.setOid(xyConvey.getId());
        rewardbalanceLog.setNum(xyConvey.getNum());
        rewardbalanceLog.setStatus(1L);
        rewardbalanceLog.setAddtime(System.currentTimeMillis() / 1000);
        rewardbalanceLog.setType(6L);//
        balanceLogService.insertXyBalanceLog(rewardbalanceLog);

        return AjaxResult.success();
    }

    @Override
    public AjaxResult applyOrderConvey(LoginUser loginuser) {
        String userName = loginuser.getUsername();
        XyUsers xyUsers = xyUsersService.selectXyUsersByUserName(userName);

        if (null == xyUsers) {
            return AjaxResult.error("paramas error");
        }

        if (xyUsers.getBalance().compareTo(new BigDecimal(5)) < 0) {
            return AjaxResult.error("yhzhyebz");
        }
        return AjaxResult.success(sdComponent.checkSelectedGoodsList(xyUsers));
    }

    @Override
    public List<XyConvey> selectUnPayConvey(Long id) {
        return xyConveyMapper.selectUnPayConvey(id);
    }
}
